<?php
namespace src;
use classlib\input;
use src\logic\Cadmin;
use classlib\core\lang;
use classlib\core as C;
use classlib\core\controller;
class Cmenu extends controller {
	
	public function main() {
		$view   = C\view::inst('extjs');
		$userid = Cadmin::chkaccess($view);
		$icon   = include 'icon.inc.php';
		$dlang  = lang::inst('dd');
		$view->assign_by_ref('icon', $icon);
		$view->assign('status', $dlang->get('sh0006'));
		$view->assign('ishow', $dlang->get('sh0008'));
		$view->assign('isdefault', $dlang->get('sh0007'));
		$view->assign_by_ref('title', Cadmin::$name);
		$view->display('core/menu.ext.js');
	}
	
	/**
	 * @desc    重新加载各个模块文件下的子模块
	 * @doc     模块载入
	 * @access  需要授权 
	 */
	public function doaccess() {
		$view  = C\view::inst('json');
		Cadmin::chkaccess($view);
		$ids   = input::get_post('ids');
		$ids   = explode(',', $ids);
		$ids   = array_filter($ids, 'is_numeric');
		$lang  = C\lang::inst('adm');
		if (empty($ids) || !is_array($ids)) {
			$view->assign_error(1, $lang->txt('common', 40002));
		}
		foreach ($ids as $id) {
			$module = C\model::load('main.sys.module')->get_one($id);
			if (empty($module)) {
				continue;
			}
			$action = trim($module['action'], '/');
			//定位到查找的控制器权限
			$index  = strpos($action, '.');
			if ($index !== false) {
				$action = substr($action, 0, $index);
			}
			$segms  = explode('/', $action);
			$file   = C\config::$appdir.'/controller';
			$do     = 'main';
			$ns     = '_'.array_shift($segms);
			if ($ns != basename(C\config::$appdir)) {
				array_unshift($segms, $ns);
			}
			foreach ($segms as $idx=>$item) {
				$file .= '/'.$item;
				if (file_exists($file.'.do.php')) {
					if (isset($segms[$idx+1])) {
						$do = $segms[$idx+1];
					}
					break;
				}
			}
			//文件存在的情况记录
			if (!file_exists($file.'.do.php')) {
				continue;
			}
			$class = 'src\\'.C\router::CTRL_PREDIX.basename($file);
			if (!class_exists($class, false)) {
				require $file.'.do.php';
			}
			$rinst = new \ReflectionClass($class);
			$res   = $rinst->getMethods(\ReflectionMethod::IS_PUBLIC);
			$access= array();//已经加载的配置信息
			foreach ($res as $mitem) {
				if ($mitem->isPublic() && !$mitem->isStatic()) {
					$doc = $mitem->getDocComment();
					//代表需要权限验证
					if (strstr($doc, '@access')) {
						$name   = $mitem->getName();
						$name   = basename($name);
						$flag   = preg_match('/@doc([^\n]+)/', $doc, $title);
						$title  = $flag? trim($title[1]):$name;
						$flag   = preg_match('/@desc([^\n]+)/', $doc, $memo);
						$memo   = $flag? trim($memo[1]):$lang->txt('common', 40006);
						$saction= '';
						if (strrpos($action, '/'.$do) !== false) {
							$saction  = str_replace($do, $name, $module['action']);
						} else {
							$saction  = $action.'/'.$name;
						}
						$where  = array('pid'=>$id, 'action'=>$saction);
						$oid    = C\model::load('main.sys.module')->isexist($where);
						if ($oid > 0) {
							$data = array('title'=>$title, 'title_en'=>$title, 'status'=>1, 'memo'=>$memo);
							C\model::load('main.sys.module')->save($oid, $data);
						} else {
							$data = array('pid'=>$id, 'action'=>$saction, 'title_en'=>$title, 'title'=>$title, 'status'=>1, 'memo'=>$memo);
							$oid  = C\model::load('main.sys.module')->new_one($data);
						}
						$access[] = $oid;
					}
				}
			}
			//清理取消授权的信息
			$where= array('pid'=>$id);
			if ($access) {
				$where[] = array('id', $access, \classlib\orm::OP_NOTIN);
			}
			$ids  = C\model::load('main.sys.module')->get_column(0, -1, $where, 'id');
			if ($ids) {
				C\model::load('main.sys.module')->get_orm()->where('id', $ids, \classlib\orm::OP_IN)->delete();
				C\model::load('main.sys.module')->set_ver();
				C\model::load('main.sys.access')->get_orm()->where('menuid', $ids, \classlib\orm::OP_IN)->delete();
				C\model::load('main.sys.access')->set_ver();
			}
		}
	}
	 
	
	/**
	 * 获取顶级模块菜单
	 * Enter description here ...
	 */
	public function doupmod() {
		$view  = C\view::inst('json');
		Cadmin::chkaccess($view);
		$pid   = (int)input::post('pid');
		$where = array('pid'=>$pid);
		$list  = C\model::load('main.sys.module')->get_list(0, -1, $where, 'id, title'); 
		if (!is_array($list)) {
			$list = array();
		}
		$lang   = C\lang::inst('adm');
		array_unshift($list, array('id'=>'0', 'title'=>$lang->txt('common', 40005)));
		$view->assign_by_ref('dataset', $list);
		$view->display();
	}
	
	/**
	 * @desc    更新以及编辑权限功能模块
	 * @doc     编辑模块
	 * @access  需要授权
	 */
	public function dosave() {
		$view  = C\view::inst('json');
		Cadmin::chkaccess($view);
		$data  = array();
		$filter = new \classlib\validator\auditor();
		$lang   = C\lang::inst('adm');
		$filter->lang($lang);
		try {
			$data['memo']     = $filter->reset('memo')->required()->minlen(1)->run();
			$data['title']    = $filter->reset('title')->required()->lbetween(1, 64)->run();
			$data['title_en'] = $filter->reset('title_en')->required()->lbetween(1, 64)->run();
			$data['action']   = $filter->reset('action')->required()->minlen(3)->run();
			$data['isdefault']= $filter->reset('isdefault')->required()->numeric()->lbetween(0, 1)->run();
			$data['ishow']    = $filter->reset('ishow')->required()->numeric()->lbetween(0, 1)->run();
			$data['status']   = $filter->reset('status')->required()->numeric()->lbetween(0, 1)->run();
		} catch (\classlib\validator\AuditorException $e) {
			$view->assign_error($e->getField(), $e->getMessage());
		} catch (\Exception $e) {
			$view->assign_error($e->getCode(), $e->getMessage());
		}
		$id 			= (int)input::post('id');
		$ppid			= (int)input::post('ppid');
		$data['pid'] 	= (int)input::post('pid');
		if($data['pid'] < 1) {
			$data['pid']= $ppid;
		}
		$data['icon']   = input::post('sicon');
		if(empty($data['icon'])) {
			$data['icon']   = 'icon-default';
		}
		$data['icon']		= ' '.$data['icon'];
		$data['order']   	= (int)input::post('order');
		if($id > 0) {
			C\model::load('main.sys.module')->save($id, $data);
		} else {
			C\model::load('main.sys.module')->new_one($data);
		}
		$view->display();
	}
	
	/**
	 * @desc    删除模块功能，只能删除子模块
	 * @doc     删除功能
	 * @access  需要授权
	 */
	public function doremove() {
		$view  = C\view::inst('json');
		Cadmin::chkaccess($view);
		$ids   = input::post('ids');
		$ids   = explode(',', $ids);
		$ids   = array_filter($ids, 'is_numeric');
		$lang  = C\lang::inst('adm');
		if (!$ids) {
			$view->assign_error('1', $lang->txt('common', 40002));
		}
		foreach ($ids as $id) {
			if (!is_numeric($id) || $id < 1) {
				continue;
			}
			C\model::load('main.sys.module')->delete($id);
			C\model::load('main.sys.access')->get_orm()->where('menuid', $id)->delete();
		}
		C\model::load('main.sys.access')->set_ver();
		$view->display();
	}
	
	/**
	 * 获取权限模块树形菜单信息
	 * Enter description here ...
	 */
	public function dotree() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		$status = (int)input::get_post('status');
		$where  = array();
		if (!$status) {
			$where['status'] = 1;
		}
		$sort   = array('pid'=>\classlib\orm::ASC, '`order`', \classlib\orm::ASC);
		$list   = C\model::load('main.sys.module')->get_list(0, -1, $where, '*', $sort);
		$loop   = 0;
		$tree   = array();
		$lang   = C\lang::inst('adm');
		while (!empty($list)) {
			foreach ($list as $key=>$item) {
				$title = $item['title'].'['.$item['title_en'].']';
				$item['sicon']   = empty($item['icon'])? 'icon-unknown':trim($item['icon']);
				unset($item['icon']);
				$item['iconCls'] = 'icon '.$item['sicon'];
				$item['text']    = ($item['status'])? $title:$title.$lang->txt('common', 40009);
				$item['checked'] = false;
				if($status) {
					$item['text']  .= '----'.$item['memo'].'----'.$item['id'];
					$item['action'] = trim($item['action']);
					if ($item['ishow'] == 0 || empty($item['action'])) {
						$item['checked']= '';
					}
				}
				if (Cadmin::mk_tree($item, $tree)) {
					unset($list[$key]);
				}
			}
			if ($loop++ > 9) {
				break;
			}
		}
		ob_end_clean();
		$tree = json_encode($tree);
		echo $tree;
	}
}